#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>

#define PAGER       "/bin/more"
#define MAXLINE     1024

int main(int argc, char *argv[])
{
    int n;
    int fd[2], file_fd;
    pid_t pid;
    char *pager, *argv0;
    char line[MAXLINE];

    if (argc != 2)
    {
        fprintf(stderr, "usage: %s <pathname>\n", argv[0]);
        exit(0);
    }

    if ((file_fd = open(argv[1], O_RDONLY)) < 0)
    {
        perror("open error");
        exit(0);
    }

    if (pipe(fd) < 0)
    {
        perror("pipe error");
        exit(0);
    }

    if ((pid = fork()) != 0)
    {
        close(fd[0]);
        
        while ((n = read(file_fd, line, MAXLINE)) > 0)
            if (write(fd[1], line, n) < n)
            {
                perror("write error");
                exit(0);
            }

        close(fd[1]);

        wait(NULL);
    }
    else
    {
        close(fd[1]);
    
        if (fd[0] != STDIN_FILENO)
        {
            if (dup2(fd[0], STDIN_FILENO) < 0)
            {
                perror("dup2 error");
                exit(0);
            }
            
            close(fd[0]);
        }

        if ((pager = getenv("PAGER")) == NULL)
            pager = PAGER;

        if ((argv0 = strrchr(pager, '/')) != NULL)
            argv0 ++;
        else
            argv0 = pager;

        if (execl(pager, argv0, NULL) < 0)
        {
            perror("execl error");
        }
    }

    return 0;
}
